package cn.besbing.server.config.shiro;


import cn.besbing.model.entities.primary.DlPermission;
import cn.besbing.model.entities.primary.DlRole;
import cn.besbing.model.entities.primary.SmUser;
import cn.besbing.server.service.primary.CustomerSqlServiceImpl;
import cn.besbing.server.service.primary.PrimaryDlPermissionServiceImpl;
import cn.besbing.server.service.primary.PrimaryDlRoleServiceImpl;
import cn.besbing.server.service.primary.PrimarySmuserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class CustomRealm extends AuthorizingRealm {

    {
        super.setName("customRealm");
    }

    @Autowired
    private PrimarySmuserServiceImpl primarySmuserService;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 自动注入
     */
    @Autowired
    private PrimarySmuserServiceImpl smuserService;

    @Autowired
    private PrimaryDlPermissionServiceImpl dlPermissionService;

    @Autowired
    private PrimaryDlRoleServiceImpl dlRoleService;

    @Autowired
    private CustomerSqlServiceImpl customSqlService;


    /**
     * @param principalCollection 传过来的凭证
     * @return add了roles和permissions后的AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();/*
        SmUser smUser = (SmUser) principalCollection.getPrimaryPrincipal();
        //添加角色
        authorizationInfo.addRole(smUser.getRole());
        //添加权限
        authorizationInfo.addStringPermissions(smUser.getPermissions());*/
        String usercode = customSqlService.selectOne("select user_code from sm_user where user_name = '" + principalCollection.getPrimaryPrincipal() + "'");
        List<DlRole> roleList = new ArrayList<>();
        List<DlPermission> permissionList = new ArrayList<>();
        roleList = dlRoleService.findRoleByUsername(usercode);
        for (DlRole dlRole : roleList){
            authorizationInfo.addRole(dlRole.getRolename());
            try{
                permissionList = dlPermissionService.findPermissionByRoleId(dlRole.getRoleid());
            }catch(Exception e){
                logger.error(e.getStackTrace().toString());
            }
            for (DlPermission dlPermission : permissionList){
                authorizationInfo.addStringPermission(dlPermission.getPermission());
            }
        }
        return authorizationInfo;
    }

    /**
     *
     * @param authenticationToken   usernameandpasswordtoken
     * @return   传进来的token
     * @throws AuthenticationException   校验不通过的返回
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String pwd = new String((char[])authenticationToken.getCredentials());
        SmUser smUser = primarySmuserService.selectUserByCode(username);
        if (smUser != null && !"".equals(pwd) && pwd.equals(smUser.getUserPassword())){
            return new SimpleAuthenticationInfo(smUser.getUserName(), smUser.getUserPassword(),"customRealm");
        }else {
            return null;
        }
    }
}

